import { http } from '@/plugins/axios'
import type { MenuOption } from 'naive-ui'

const collection = ref<ResponsePageResult<MenuModel>>()

export default () => {
  const menus = ref<MenuOption[] | MenuModel[]>()
  const params = ref({
    key: '',
    page: 1,
    per_page: 5,
  })
  const model = ref<MenuModel>()

  const load = async () => {
    collection.value = await http.request<MenuModel[], ResponsePageResult<MenuModel>>({
      url:
        `menu?` +
        Object.entries(params.value)
          .map(([k, v]) => `${k}=${v}`)
          .join('&'),
    })

    menus.value = collection.value!.data
  }

  const find = async (id: any) => {
    const { data } = await http.request<MenuModel>({
      url: `menu/${id}`,
    })
    model.value = data
  }

  const add = async (model: MenuModel) => {
    const data = await http.request({ url: 'menu', method: 'POST', data: model })
    return data
  }

  const update = async (model: MenuModel) => {
    const data = await http.request<any, ResponseResult<any>>({
      url: `menu/${model.id}`,
      method: 'PUT',
      data: model,
    })
    return data
  }

  const del = async (model: MenuModel) => {
    await http.request({ url: `menu/${model.id}`, method: 'DELETE', data: model })
    load()
  }

  return { collection, model, load, params, find, add, update, del, menus }
}
